package com.tsinghuabigdata.edu.ddmath.module.ddwork.bean;

import android.os.AsyncTask;
import android.os.SystemClock;
import android.text.TextUtils;

import com.tsinghuabigdata.edu.ddmath.ZxApplication;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.AppAsyncTask;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.constant.ErrTag;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.DDWorkManager;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.WorkCommitListener;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.base.util.NetworkUtil;
import com.tsinghuabigdata.edu.ddmath.requestHandler.MyLearnService;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * 保存在本地的作业信息
 */
public class LocalWorkInfo implements Serializable {

    private static final long serialVersionUID = 6877455798122949600L;

    public final static int WORK_NONE = 0;              //未处理状态，默认
    public final static int WORK_COMMITING = 1;         //提交中
    public final static int WORK_COMMITED = 3;          //提交完成
    public final static int WORK_COMMITFAIL = 2;        //提交失败

    //作业ID
    private String workId;

    //页信息
    private ArrayList<LocalPageInfo> pageList = new ArrayList<>();

    //状态
    private int workStatus = WORK_NONE;

    //for save
    public JSONObject getJsonObject(){
        JSONObject json = new JSONObject();
        try {
            if( workStatus == WORK_COMMITING || workStatus == WORK_COMMITFAIL ){
                json.put( "workStatus", WORK_COMMITFAIL );
            }else {
                json.put( "workStatus", workStatus );
            }
            json.put( "workId", workId );       //

            JSONArray jsonArray = new JSONArray();
            for( LocalPageInfo pageInfo : pageList ){
               jsonArray.put( pageInfo.getJsonObject() );
            }
            json.put( "pageList", jsonArray );       //
        }catch (Exception e){
            AppLog.i(ErrTag.TAG_JSON, e.toString() );
        }

        return json;
    }

    public JSONArray getUploadData(){
        JSONArray jsonArray = new JSONArray();
        for( LocalPageInfo pageInfo : pageList ){
            jsonArray.put( pageInfo.getJson() );
        }
        return jsonArray;
    }



    //----------------------------------------------------------------------------
    public int getWorkStatus() {
        return workStatus;
    }

//    public void setWorkStatus(int workStatus) {
//        this.workStatus = workStatus;
//    }

    public String getWorkId() {
        return workId;
    }

    public void setWorkId(String workId) {
        this.workId = workId;
    }

    public ArrayList<LocalPageInfo> getPageList() {
        return pageList;
    }

    public void setPageList(ArrayList<LocalPageInfo> pageList) {
        this.pageList = pageList;
    }

    //----------------------------------------------------------------------------
    private ArrayList<WorkCommitListener> mCommitListeners;
    private SubmitQuestionTask mSubmitQuestionTask;

    public void setWorkCommitListener(ArrayList<WorkCommitListener> listeners){
        mCommitListeners = listeners;
    }

    /**
     * 上传先检查图片是否上传完成，再上传信息
     */
    public void startUploadData(){
        if( mSubmitQuestionTask==null || mSubmitQuestionTask.isCancelled() || mSubmitQuestionTask.isComplete() ){
            mSubmitQuestionTask = new SubmitQuestionTask();
            mSubmitQuestionTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }

    //
    public void stopUploadData(){
        if( mSubmitQuestionTask!=null  ){
            mSubmitQuestionTask.cancel( true );
        }
    }

//    class UploadImageListenerImpl implements UploadImageListener {
//        @Override
//        public void updateStatus(int status) {
//            if( mCommitListener!=null ){
//                mCommitListener.onSuccess( true );
//            }
//        }
//    }

    private void commitStatusChange( Object obj ){
        if( mCommitListeners!=null ){
            for( WorkCommitListener listener : mCommitListeners ){
                if( obj == null ){
                    listener.workStatus( workId, workStatus );
                }else if( obj instanceof Boolean ){
                    listener.onSuccess( workId, (Boolean)obj );
                }else if( obj instanceof Exception ){
                    listener.onFail( workId, (Exception)obj );
                }
            }
        }
    }

    //向每一页注册状态变化信息
    private void addWorkCommitListener(){
        for( LocalPageInfo pageInfo : pageList ){
            if( !TextUtils.isEmpty( pageInfo.getLocalpath()) )
                pageInfo.setPageListener( mCommitListeners );
        }
    }

    //全部启动上传
    private void startUpload(){
        for( LocalPageInfo pageInfo : pageList ){
            if( !TextUtils.isEmpty( pageInfo.getLocalpath()) )
                pageInfo.startUpload();
        }
    }

    //是否全部上传成功
    private boolean isUploadSuccess(){
        for( LocalPageInfo pageInfo : pageList ){
            if( !TextUtils.isEmpty( pageInfo.getLocalpath()) )
                if( pageInfo.getUploadStatus() != LocalPageInfo.ST_SUCC ){
                    return false;
                }
        }
        return true;
    }

    //是否上传全部动作完成
    private boolean isFinishUpload(){
        for( LocalPageInfo pageInfo : pageList ){
            if( !TextUtils.isEmpty( pageInfo.getLocalpath()) )
                if( pageInfo.getUploadStatus() == LocalPageInfo.ST_UING || pageInfo.getUploadStatus() == LocalPageInfo.ST_NONE ){
                    return false;
                }
        }
        return true;
    }

    class SubmitQuestionTask extends AppAsyncTask<String, Void, Boolean> {

        public SubmitQuestionTask(){
            workStatus = WORK_COMMITING;
            commitStatusChange( null );
        }
        @Override
        protected Boolean doExecute(String... params) throws Exception {

            //网络检测
            if( !NetworkUtil.isNetAvailable( ZxApplication.getApplication() ) ){
                throw new Exception("没有网络");
            }

            LoginInfo loginInfo = AccountUtils.getLoginUser();
            UserDetailinfo detailinfo = AccountUtils.getUserdetailInfo();
            if( loginInfo == null || detailinfo == null || detailinfo.getJoinedClassInfoList()==null || detailinfo.getJoinedClassInfoList().size()==0 ){
                throw new Exception("请登录");
            }
            MyLearnService service = ZxApplication.getLearnService();
            if( service==null ){
                throw new Exception("没有启动 LearnService");
            }

            String accessToken = loginInfo.getAccessToken();
            String studentId   = detailinfo.getStudentId();
            String classId     = detailinfo.getJoinedClassInfoList().get(0).getClassId();

            //0, 先注册监听事件
            addWorkCommitListener();

            //1，启动图片上传
            startUpload();

            //2，检测图片是否上传完成
            int index = 0;
            int count = pageList.size() * 1000;       //超时最大100s，一个最多需要检测1000次
            while( true ){
                SystemClock.sleep(100);
                index++;

                //先判断是否都上传成功
                if( isUploadSuccess() )
                    break;

                //失败或者成功，上传动作完成
                if( isFinishUpload() ){
                    throw new Exception("图片上传失败");
                }

                //超过时间，失败提示 300s
                if( index > count ){
                    throw new Exception("图片上传失败");
                }
            }

            //3，上传作业信息
            JSONArray jsonArray = getUploadData();

            //重试几次
            for( index=0; index<3;index++ ){
                try {
                    String workId = service.submitDDWorkInfo( accessToken, studentId, classId, getWorkId(), jsonArray );
                    if( !TextUtils.isEmpty(workId) )
                        return true;
                }catch (Exception e){
                    AppLog.i( e.toString() );
                }
            }

            //失败
            throw new Exception("图片数据上传失败");
        }

        @Override
        protected void onResult(Boolean success) {

            workStatus = success?WORK_COMMITED:WORK_COMMITFAIL;
            commitStatusChange( success );

            DDWorkManager workManager = DDWorkManager.getDDWorkManager();
            if( workManager == null ) return;
            workManager.saveData();

        }

        @Override
        protected void onFailure(HttpResponse<Boolean> response, Exception ex) {

            workStatus = WORK_COMMITFAIL;
            commitStatusChange( ex );

            DDWorkManager workManager = DDWorkManager.getDDWorkManager();
            if( workManager == null ) return;
            workManager.saveData();
        }
    }
}
